package com.itheima.web.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.DateFormatUtil;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.BsonArray;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserManager {

    @Reference
    private UserInfoService userInfoService;
    @Reference
    private VideoService videoService;
    @Reference
    private MovementService movementService;
    @Reference
    private CommentService commentService;
   @Autowired
   private StringRedisTemplate stringRedisTemplate;

    //用户列表
    public PageBeanVo findUserList(Integer pageNum, Integer pageSize) {
        PageBeanVo pageBeanVo = userInfoService.findUserList(pageNum, pageSize);
        List<UserInfo> userInfoList = (List<UserInfo>) pageBeanVo.getItems();
        ArrayList<UserInfoVo> userInfoVoList = new ArrayList<>();
        //向userinfo中添加状态字段
        if(userInfoList!=null){
            for (UserInfo userInfo : userInfoList) {
                Long id = userInfo.getId();
                UserInfoVo userInfoVo = new UserInfoVo();
                BeanUtils.copyProperties(userInfo,userInfoVo);
                String userState = stringRedisTemplate.opsForValue().get(id + "userState");
                //不为空,说明已被冻结
                if(userState!=null) {
                    userInfoVo.setUserStatus("2");
                }
                //如果不存在，就说明是初始状态，设置为1，正常
                else {
                    userInfoVo.setUserStatus("1");
                }
                 userInfoVoList.add(userInfoVo);
                }
            pageBeanVo.setItems(userInfoVoList);
            return pageBeanVo;
            }
        return pageBeanVo;
    }

    //用户详情信息
    public UserInfoVo findUserInfo(Long userId) {
        UserInfo userInfo = userInfoService.findByUserId(userId);
        Long id = userInfo.getId();
        //创建一个vo对象
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        String format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new DateTime(userInfo.getCreated()));
        userInfoVo.setCreated(format);
        userInfoVo.setAge(userInfo.getAge()+"");
        String userState = stringRedisTemplate.opsForValue().get(id + "userState");
        //不为空,说明已被冻结
        if(userState!=null) {
            userInfoVo.setUserStatus("2");
        }
        //如果不存在，就说明是初始状态，设置为1，正常
        else {
            userInfoVo.setUserStatus("1");
        }
            return userInfoVo;
    }

    //查询指定用户的视频列表
    public PageBeanVo findUserVideoList(Long uid, Integer pageNum, Integer pageSize) {
        PageBeanVo pageBeanVo = videoService.findUserVideoList(uid, pageNum, pageSize);

        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                //3-1 创建videoVo
                VideoVo videoVo = new VideoVo();

                //3-2 设置用户信息
                UserInfo userInfo = userInfoService.findByUserId(video.getUserId());
                BeanUtil.copyProperties(userInfo, videoVo);

                //3-3 设置视频信息
                BeanUtil.copyProperties(video, videoVo);
                videoVo.setCover(video.getPicUrl());//设置封面图片
                videoVo.setSignature(video.getText());//设置文案
                videoVo.setHasLiked(1);//todo  实战修改

                //3-4  收集
                videoVoList.add(videoVo);
            }
        }
        pageBeanVo.setItems(videoVoList);
        return pageBeanVo;
    }

    //用户动态列表
    public PageBeanVo findUserMovementList(Long uid, Integer stateInt, Integer pageNum, Integer pageSize) {
        //1. 调用service查询
        PageBeanVo pageBeanVo = movementService.findUserMovementList(uid, stateInt, pageNum, pageSize);

        //2. 处理返回结果
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfoService.findByUserId(movement.getUserId()));
                movementVo.setMovement(movement);
                String format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new DateTime(movement.getCreated()));
                //DateUtil.offsetDay(new DateTime(movement.getCreated()), 0).toDateStr()
                movementVo.setCreateDate(format);
                movementVoList.add(movementVo);
            }
        }
        pageBeanVo.setItems(movementVoList);
        return pageBeanVo;
    }

    //查询用户动态详情
    public MovementVo findMovementDetail(String movementId) {
        MovementVo movementVo = new MovementVo();
        Movement movement = movementService.findMovementById(movementId);
        movementVo.setUserInfo(userInfoService.findByUserId(movement.getUserId()));
        movementVo.setMovement(movement);
        movementVo.setCreateDate(DateUtil.offsetDay(new Date(movement.getCreated()),0).toDateStr());
        return movementVo;
    }

    //查询动态评论列表
    public PageBeanVo findMovementCommentList(String movementId, Integer pageNum, Integer pageSize) {
        //1. 调用service查询
        PageBeanVo pageBeanVo = commentService.findMovementCommentList(movementId, pageNum, pageSize);

        //2. 处理返回结果
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> commentVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                //1. 创建CommentVo
                CommentVo commentVo = new CommentVo();

                //2. 设置用户信息
                UserInfo userInfo = userInfoService.findByUserId(comment.getUserId());
                commentVo.setAvatar(userInfo.getAvatar());
                commentVo.setNickname(userInfo.getNickname());


                //3. 设置评论信息
                commentVo.setId(comment.getId().toHexString());
                commentVo.setContent(comment.getContent());
                commentVo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated())));

                //4. vo放入临时集合
                commentVoList.add(commentVo);
            }
        }

        pageBeanVo.setItems(commentVoList);
        return pageBeanVo;
    }

    //todo 动态审核——通过：待审核、驳回动态
    public Map<String, String> passMovement(String[] movementIdArr) {
        //遍历，获取全部movementId
        for (String movementId : movementIdArr) {
            Movement movement = movementService.findMovementById(movementId);
            movement.setState(1);
            //调用修改动态的方法，把动态通过；
            movementService.updateMovement(movement);
        }

        Map<String, String> map = new HashMap<>();
        map.put("message","相关动态已审核通过！");
        return map;
    }
    //todo 动态审核——驳回待审核动态
    public Map<String, String> rejectMovement(String[] movementIdArr) {
        //遍历，获取全部movementId
        for (String movementId : movementIdArr) {
            Movement movement = movementService.findMovementById(movementId);
            movement.setState(2);
            //调用修改动态的方法，将动态驳回；
            movementService.updateMovement(movement);
        }
        Map<String, String> map = new HashMap<>();
        map.put("message","相关动态已驳回！");
        return map;
    }
    //冻结用户
    public String freezeUser(Integer userId, Integer freezingRange, Integer freezingTime, String reasonsForFreezing, String frozenRemarks) {
        //将冻结原因存入redis
        stringRedisTemplate.opsForValue().set(userId+"freezeReason",reasonsForFreezing);
            //冻结三天
            if(freezingTime==1){

                stringRedisTemplate.opsForValue().set(userId+"userState","2",60*60*24*3);
                //冻结登录
                if (freezingRange==1){
                    stringRedisTemplate.opsForValue().set(userId+"loginState","2",60*60*24*3);
                }
                //冻结发言
                if(freezingRange==2){
                    stringRedisTemplate.opsForValue().set(userId+"speakState","2",60*60*24*3);
                }
                //冻结发布动态
                if(freezingRange==3){
                    stringRedisTemplate.opsForValue().set(userId+"publishCommentState","2",60*60*24*3);
                }
            }
            //冻结七天
            if(freezingTime==2){
                stringRedisTemplate.opsForValue().set(userId+"userState","2",60*60*24*7);
                //冻结登录
                if (freezingRange==1){
                    stringRedisTemplate.opsForValue().set(userId+"loginState","2",60*60*24*7);
                }
                //冻结发言
                if(freezingRange==2){
                    stringRedisTemplate.opsForValue().set(userId+"speakState","2",60*60*24*7);
                }
                //冻结发布动态
                if(freezingRange==3){
                    stringRedisTemplate.opsForValue().set(userId+"publishCommentState","2",60*60*24*7);
                }
            }
            //永久冻结
            if(freezingTime==3){

                stringRedisTemplate.opsForValue().set(userId+"userState","2");
                //冻结登录
                if (freezingRange==1){
                    stringRedisTemplate.opsForValue().set(userId+"loginState","2");
                }
                //冻结发言
                if(freezingRange==2){
                    stringRedisTemplate.opsForValue().set(userId+"speakState","2" );
                }
                //冻结发布动态
                if(freezingRange==3){
                    stringRedisTemplate.opsForValue().set(userId+"publishCommentState","2");
                }
            }
            return "冻结成功";
    }
//解冻
    public void unFreeze(Integer id, String reasonsForThawing) {
        stringRedisTemplate.delete(stringRedisTemplate.keys(id+"*"));
    }
}
